package com.henry.studyj;
import java.lang.reflect.Method;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;

public class XClassLoader extends ClassLoader {

    public static void main(String[] args) throws Exception{
        ClassLoader cl =new XClassLoader();
        String className="Hello";
        Class<?> entity =cl.loadClass(className);
        if(entity ==null){
            return;
        }
        //查看有哪些方法
        for(Method m : entity.getDeclaredMethods())
        {
            System.out.println("方法名:"+m.getName());
        }

        //实例化对象
        Object obj= entity.getDeclaredConstructor().newInstance();
        Method m1=entity.getDeclaredMethod("hello");
        m1.invoke(obj);
    }

    @Override
    protected  Class<?> findClass(String name) throws ClassNotFoundException {
       //构造完整文件名
        String fullName=name+".xlass";
        //获取文件流
        InputStream stream  =XClassLoader.class.getClassLoader().getResourceAsStream(fullName);

        try {
            int length = stream.available();
            byte[] bytes = new byte[length];
            //将内容流转换成byte数组
            stream.read(bytes);
            //解码内容流
            byte[] realContent = decode(bytes);
            //通知底层定义文件
            return defineClass(name, realContent, 0, realContent.length);
        }
        catch (Exception e){
            System.out.println("出错了："+e.getMessage());
        }
        return null;
    }

    //解码
    public static byte[] decode(byte[] data){
      byte[] realContent = new byte[data.length];
      for(int i =0;i<data.length;i++){
          realContent[i]=(byte)(255-data[i]);
      }
      return realContent;
    }

}
